package com.app.couponsharelife.ui.main.home.good

import android.app.AlertDialog
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.provider.MediaStore
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.utils.AppUtils
import kotlinx.android.synthetic.main.activity_scan_pic.*
import java.io.FileNotFoundException

class ScanPicActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_scan_pic

    private var mViews: MutableList<View> = ArrayList()

    private val list = arrayListOf<Any>()

    private var position = 0

    override fun initViews() {
        AppUtils.initImmersionBar(this,false)
        list.addAll(intent!!.getSerializableExtra("pics") as ArrayList<Any>)
        position = intent!!.getIntExtra("position", 0)
        initViewPager()
    }

    private fun initViewPager() {
        for (i in 0 until list.size) {
            val imageView = ImageView(this)
            imageView.setOnClickListener { finish() }
            imageView.setOnLongClickListener {
                val builder = AlertDialog.Builder(this@ScanPicActivity)
                builder.setTitle("提示")
                builder.setMessage("是否保存图片")
                builder.setPositiveButton("确定") { dialog, which ->
                    dialog.dismiss()
                    savePic((imageView.drawable as BitmapDrawable).bitmap)
                }
                builder.setNegativeButton("取消") { dialog, which -> dialog.dismiss() }
                builder.show()
                true
            }
            mViews.add(imageView)
            if (list[i] is String)
                Glide.with(this).asBitmap()
                        .apply(RequestOptions().placeholder(R.drawable.ic_good_place_holder))
                        .load((list[i] as String).replace(" ", ""))
                        .into(imageView)
            else
                Glide.with(this).asBitmap()
                        .apply(RequestOptions().placeholder(R.drawable.ic_good_place_holder).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE))// 不使用内存缓存 不使用磁盘缓存
                        .load(list[i])
                        .into(imageView)
        }
        mViewPager.adapter = ScanPicAdapter()
        mViewPager.offscreenPageLimit = list.size
        mViewPager.currentItem = position
        tvIndicator.text = String.format("%s/%s", position + 1, list.size)
        mViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
                tvIndicator.text = String.format("%s/%s", position + 1, mViewPager.childCount)
            }
        })
    }

    private fun savePic(bitmap: Bitmap) {
        showProgressDialog("请稍候")
        // 其次把文件插入到系统图库
        try {
            val file = AppUtils.saveBitmap(bitmap, "${AppUtils.getCurrentTime1()}.jpg", false)
            MediaStore.Images.Media.insertImage(contentResolver, file.absolutePath, file.name, null)
            // 最后通知图库更新
            sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.absolutePath)))
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }
        dismissProgressDialog()
        showToastMsg("图片已保存")
    }

    inner class ScanPicAdapter : PagerAdapter() {
        override fun isViewFromObject(view: View, arg1: Any): Boolean {
            return view == arg1
        }

        override fun getCount(): Int {
            return mViews.size
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            container.addView(mViews[position])
            return mViews[position]
        }

        override fun destroyItem(container: ViewGroup, position: Int, arg1: Any) {
            container.removeView(arg1 as View)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}
